package mycassandra

import (
	"log"
	"net"
	"os"
	"time"

	"github.com/gocql/gocql"
)

var serIp string = GetLocalIP()

// Cassandra config list
const KeySpace string = "msgkeyspace"
const user string     = "cassandra"
const password string = "cassandra"
const numCons int     = 2000

var hosts = []string{
	"172.16.175.245",
}

// CQL Session
var cqlSession = getCQLSession()

/**
* Get CQL session
*
* @author Moks
 */
func getCQLSession() *gocql.Session{
	// connect to the cluster config
	clusterConfig := gocql.NewCluster(hosts...)
	clusterConfig.Consistency    = gocql.One
	clusterConfig.ProtoVersion   = 4
	clusterConfig.Keyspace       = KeySpace
	clusterConfig.NumConns       = numCons
	clusterConfig.ConnectTimeout = time.Second * 100
	clusterConfig.Authenticator  = gocql.PasswordAuthenticator{Username: user, Password: password}
	clusterConfig.DisableInitialHostLookup = true
	_session, err := clusterConfig.CreateSession()

	if err != nil {
		log.Fatal(err.Error())
	}
	_session.SetTrace(gocql.NewTraceWriter(_session, os.Stdout))
	return _session
}

/**
* Insert msg
* @param appId
* @param msg
* @author Moks
*/
func Insert(appId string,ownerId string,typeId string,msgId string, msg string,currentTime time.Time,sign string) {

	currentTimeStr := currentTime.Format("2006-01-02 15:04:05")
	if err := cqlSession.Query(`INSERT INTO msg (app_id,owner_id,type_id,msg_id,msg,status,sign,ser_ip,created_stamp,updated_stamp) 
                                      VALUES (?, ?, ?, ?, ?, ?,? ,?,? , ?)`,
		appId, ownerId,typeId,msgId, msg,1,sign,serIp,currentTimeStr,currentTimeStr).Exec(); err != nil {
		log.Fatal(err)
	}
}


/**
* Get local IP
 */
func GetLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, address := range addrs {
		// check the address type and if it is not a loopback the display it
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}
